import requests
import unittest
import yaml
import time
import concurrent.futures
import contextlib
from setup_common import get_shared_ip, get_shared_headers, generate_url
import io
import multiprocessing

class binsizeTest(unittest.TestCase):

    def setUp(self):
        self.ip = get_shared_ip()
        self.Readfile = open('初始化库位.yaml', 'r', encoding='utf-8')
        self.binseturl = generate_url(self.ip, "binset")
        self.headers = get_shared_headers()
        self.binsizeinfo = {}

    def capture_output(self, func, *args):
        with io.StringIO() as mock_stdout:
            with contextlib.redirect_stdout(mock_stdout):
                func(*args)
            return mock_stdout.getvalue()

    def test_add_binsize(self):
        res = list(yaml.full_load_all(self.Readfile))

        def upload_data(data):
            bin_name = data["bin_name"]
            bin_property = "Normal"
            bin_size = "Tiny"
            creater = "cow11023@163.com"
            payload = {
                "bin_name": bin_name,
                "bin_property": bin_property,
                "bin_size": bin_size,
                "creater": creater
            }
            try:
                response = requests.post(url=self.binseturl, json=payload, headers=self.headers).text
                print(self.binseturl)
                print(response)  # 输出响应内容
                time.sleep(0.3)
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常：{e}")
                assert self

        # 使用多线程池来并发上传数据
        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            futures = [executor.submit(upload_data, data) for data in res]

        # 等待线程池中的任务完成
        concurrent.futures.wait(futures)

        # 检查是否捕获到输出信息
        captured_output = self.capture_output(lambda: None)
        print(captured_output)

        # 判断输出数据的行数是否与初始化库位.yaml文件的条数相匹配
        output_lines = captured_output.strip().split('\n')
        self.assertTrue(all('{' or line and '}' in line for line in output_lines))

    def tearDown(self):
        self.Readfile.close()  # 显式关闭文件

if __name__ == '__main__':
    unittest.main()
